package com.liuyucheng.idea_springboot.wechat.gzh.controller;

import com.liuyucheng.idea_springboot.bean.Result;
import com.liuyucheng.idea_springboot.wechat.gzh.service.WechatGzhService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Collectors;

/**
 * 微信公众号控制层
 * @author LiuYuCheng
 * @date 2023年11月20日 11:14
 */
@Slf4j
@RestController
@RequestMapping("/wechat/gzh")
public class WechatGzhController {

    @Autowired
    private WechatGzhService wechatGzhService;

    @Value("${wechat.gzh.menuPath}")
    private String menuPath;

    @PostMapping(value = "/updateMenu")
    @ApiOperation(value = "更新菜单", notes = "更新菜单")
    public Result<Object> updateMenu(HttpServletRequest request) {
        try {
            String menuJson = Files.readAllLines(new File(menuPath).toPath()).stream().collect(Collectors.joining("\n"));
            String accessToken = wechatGzhService.getAccessToken();
            String resultJson = wechatGzhService.updateMenu(menuJson,accessToken);
            return Result.ok(resultJson);
        } catch (IOException e) {
            log.error("菜单更新异常",e);
        }

        return Result.ok("菜单更新成功");
    }

}
